/**
 * Copyright 2009 University of Washington This code is released under the GPL version 3 - with a copy of the license
 * included
 * 
 * @author Maya Hao Li
 */
package seedpod.webapp.view.seedpodwidgets;

import seedpod.exceptions.InvalidWidgetException;
import seedpod.model.AVPair;
import seedpod.model.SeedpodModel.RdbCls.FormWidget;
import seedpod.model.SeedpodModel.RdbCls.ViewWidget;
import seedpod.model.rdb.RdbValueType;
import seedpod.webapp.Seedpod;
import seedpod.webapp.view.htmlwidget.ImageButton;
import seedpod.webapp.view.htmlwidget.TextInput;

public class Date extends LimsWidget {

	// public Date(SlotMap att) {
	// super( att );
	// _data = ""; // default to display nothing
	// }

	public Date() {
	// TODO Auto-generated constructor stub
	}

	public Date(AVPair avpair) {
		super( avpair );
	}

	@Override
	public java.sql.Date getData() {
		java.sql.Date sqlDate = null;
		try {
			if ( super.getData() != null ) sqlDate = java.sql.Date.valueOf( super.getData().toString() );
		} catch (ClassCastException e) {
			setData( null );
		}
		return sqlDate;
	}

	@Override
	public FormWidget getFormWidgetType() {
		return FormWidget.DATE;
	}

	@Override
	public ViewWidget getViewWidgetType() {
		return ViewWidget.DATE;
	}

	@Override
	public String render() {
		String view = "";
		TextInput dateInput;
		// display
		dateInput = getData() == null ? new TextInput( _widgetID, "" ) : new TextInput( _widgetID, getData().toString() );
		dateInput.setCssClass( "calendarInput" );
		dateInput.setSize( 30 );

		view += dateInput.render() + "&nbsp;";
		view += renderCalendarLookup();
		return view;
	}

	private String renderCalendarLookup() {
		String calendarImgUrl = Seedpod.getAbsoluteUrl( "/images/calendar.gif" );
		String calendarJsUrl = Seedpod.getAbsoluteUrl( "/javascript/calendar.js" );
		String calendarHtml = Seedpod.getAbsoluteUrl( "/lims/calendar.html" );
		String calendarTarget = _widgetID;
		String calendarJsAction = ATT( "onClick",
				"openCalendar(this, '" + calendarTarget + "','" + calendarHtml + "'); return false;" );

		ImageButton calendarBtn = new ImageButton( "calendarLookup", calendarImgUrl, "#", "Date Lookup" );
		calendarBtn.addJavascript( calendarJsUrl, calendarJsAction );
		calendarBtn.setAlign( "absmiddle" );

		return calendarBtn.render();
	}

	public boolean validateSubmissionData() {
		try {
			java.sql.Date.valueOf( super.getData().toString() );
			return true;
		} catch (ClassCastException ce) {
			return false;
		}
	}

	@Override
	public void validateWidget() throws InvalidWidgetException {
		if ( !getAttribute().getRdbValueType().equals( RdbValueType.DATE ) )
			throw new InvalidWidgetException( "Widget is valid for Date type only. " );
	}
}
